<script setup lang="ts">
import { useOrderStore } from "@/stores/orderStore";
import type { EditAdressObject } from "@/types/Order";
import message from "@/utils/message";

// 用于控制弹框的显示和隐藏
const visible = ref(false);
// 对当前的操作进行标识 (添加或修改)
const flag = reactive({ isAlter: false });
// 向外暴露用于控制弹框显示和隐藏的响应式状态

//表单初始值
const initalValues: EditAdressObject = {
  //收货人姓名
  receiver: "",
  //联系方式
  contact: "",
  //所在省份编码
  provinceCode: "",
  //所在城市编码
  cityCode: "",
  //所在区/县编码，
  countyCode: "",
  //详细地址
  address: "",
  //邮政编码
  postalCode: "",
  //地址标签，以英文逗号分割
  addressTags: "",
  //是否为默认，0位是，1为否
  isDefault: false,
};

const formValues = ref<EditAdressObject>({ ...initalValues });

// 获取订单 store 对象
const orderStore = useOrderStore();
//声明要触发的自定义事件
const emit = defineEmits<{ (e: "onAddressEditSuccess", id: string): void }>();
//添加或者修改收货地址
async function onAddressEdit() {
  //定义数据
  const reqParams = {
    ...formValues.value,
    isDefault: formValues.value ? 0 : 1,
  };
  console.log(reqParams);

  //捕获错误
  try {
    const id = !flag.isAlter
      ? await orderStore.addAddress(reqParams)
      : await orderStore.updateAddress(reqParams);

    message({
      type: "success",
      msg: `收货地址${flag.isAlter ? "修改" : "添加"}成功`,
    });
    // 当收货地址列表添加成功以后 先更新本地收货地址列表
    await orderStore.getAddress();
    // 通知父组件收货地址添加或修改成功
    emit("onAddressEditSuccess", id);
    // 关闭弹框
    visible.value = false;
  } catch (error) {
    console.log(error);
    message({
      type: "error",
      msg: `收货地址${flag.isAlter ? "修改" : "添加"}失败`,
    });
  }
}
// 向外暴露用于控制弹框显示和隐藏的响应式状态
defineExpose({ visible, formValues, flag });
watch(visible, () => {
  // 如果弹框被销毁了
  if (!visible.value) {
    // 清空表单值
    formValues.value = {
      ...initalValues,
    };
  }
});
</script>

<template>
  <XtxDialog
    v-model:visible="visible"
    :title="`${flag.isAlter ? '修改' : '添加'}收货地址`"
  >
    <template #body>
      <div class="address-edit">
        <div class="xtx-form">
          <div class="xtx-form-item">
            <div class="label">收货人：</div>
            <div class="field">
              <input
                class="input"
                v-model="formValues.receiver"
                placeholder="请输入收货人"
              />
            </div>
          </div>
          <div class="xtx-form-item">
            <div class="label">手机号：</div>
            <div class="field">
              <input
                class="input"
                v-model="formValues.contact"
                placeholder="请输入手机号"
              />
            </div>
          </div>
          <div class="xtx-form-item">
            <div class="label">地区：</div>
            <div class="field">
              <XtxCity
                v-model:full-location="formValues.fullLocation"
                @address-code-changed="
                  (formValues.provinceCode = $event.provinceCode),
                    (formValues.cityCode = $event.cityCode),
                    (formValues.countyCode = $event.countyCode)
                "
              />
            </div>
          </div>
          <div class="xtx-form-item">
            <div class="label">详细地址：</div>
            <div class="field">
              <input
                class="input"
                v-model="formValues.address"
                placeholder="请输入详细地址"
              />
            </div>
          </div>
          <div class="xtx-form-item">
            <div class="label">邮政编码：</div>
            <div class="field">
              <input
                class="input"
                v-model="formValues.postalCode"
                placeholder="请输入邮政编码"
              />
            </div>
          </div>
          <div class="xtx-form-item">
            <div class="label">地址标签：</div>
            <div class="field">
              <input
                class="input"
                v-model="formValues.addressTags"
                placeholder="请输入地址标签，逗号分隔"
              />
            </div>
          </div>
          <div class="xtx-form-item">
            <div class="label">是否设置为默认地址：</div>
            <div class="field">
              <input
                type="checkbox"
                v-model="(formValues.isDefault as boolean)"
                class="checkbox"
              />
            </div>
          </div>
        </div>
      </div>
    </template>
    <template #footer>
      <XtxButton
        @click="visible = false"
        type="gray"
        style="margin-right: 20px"
      >
        取消
      </XtxButton>
      <XtxButton type="primary" @click="onAddressEdit">确认</XtxButton>
    </template>
  </XtxDialog>
</template>

<style scoped lang="less">
.xtx-dialog {
  :deep(.wrapper) {
    width: 780px;
    .body {
      font-size: 14px;
    }
  }
  .xtx-city {
    width: 320px;
    :deep(.select) {
      height: 50px;
      line-height: 48px;
      display: flex;
      padding: 0 10px;
      justify-content: space-between;
      .placeholder {
        color: #ccc;
      }
      i {
        color: #ccc;
        font-size: 18px;
      }
      .value {
        font-size: 14px;
      }
    }
    :deep(.option) {
      top: 49px;
    }
  }
}
.xtx-form {
  padding: 0;
  .xtx-form-item {
    width: auto;
    &:last-child {
      padding-bottom: 0;
    }
  }
  input {
    outline: none;
    &::placeholder {
      color: #ccc;
    }
  }
}
</style>
